#!/bin/bash

# ================= 配置部分 =================
SERVICE_NAME="table-extraction"
LOG_DIR="./logs"
ACCESS_LOG="$LOG_DIR/access.log"
ERROR_LOG="$LOG_DIR/error.log"
GUNICORN_CMD="gunicorn -c gunicorn_config.py extraction:extraction"
PID_FILE="$LOG_DIR/gunicorn.pid"

MAX_WAIT_SECONDS=10

# 创建日志目录和文件
mkdir -p "$LOG_DIR"
touch "$ACCESS_LOG" "$ERROR_LOG"

# ================ 工具函数 ================
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

check_port() {
    local port=$(grep -oP 'bind\s*=\s*"([^"]+)' gunicorn_config.py | cut -d':' -f2 | tr -d '"')
    if [[ -z "$port" ]]; then
        port=9092
        log "⚠️ 无法从配置中读取端口，默认使用 9092"
    fi

    if ss -tuln | grep ":$port" >/dev/null; then
        log "❌ 端口 $port 被占用，请先释放或修改 bind 端口"
        return 1
    else
        return 0
    fi
}

get_pid_from_file() {
    if [ -f "$PID_FILE" ]; then
        cat "$PID_FILE" 2>/dev/null | grep -E '^[0-9]+$'
    fi
}

get_pids() {
    local pids_from_file
    pids_from_file=$(get_pid_from_file)
    if [ -n "$pids_from_file" ]; then
        echo "$pids_from_file"
    else
        pgrep -f "$SERVICE_NAME" 2>/dev/null
    fi
}


check_status() {
    local pids
    pids=$(get_pids)
    if [ -z "$pids" ]; then
        log "$SERVICE_NAME 服务未运行。"
        return 1
    else
        log "$SERVICE_NAME 服务正在运行 (PID: $pids)"
        return 0
    fi
}

clean_logs() {
    > "$ACCESS_LOG"
    > "$ERROR_LOG"
    log "✅ access.log 和 error.log 已清空"
}
stop_service() {
    local pids
    pids=$(get_pids)

    if [ -z "$pids" ]; then
        log "没有找到正在运行的 $SERVICE_NAME 服务。"
        return 0
    fi

    log "正在停止旧服务 (PID: $pids)..."
    kill $pids 2>/dev/null

    local waited=0
    while [ $waited -lt $MAX_WAIT_SECONDS ]; do
        if ! get_pids >/dev/null; then
            log "旧服务已成功停止。"
            return 0
        fi
        sleep 1
        ((waited++))
    done

    log "警告：等待超时，强制终止进程..."
    kill -9 $pids 2>/dev/null
    sleep 1

    if ! get_pids >/dev/null; then
        log "服务已强制终止。"
        return 0
    else
        log "错误：无法完全停止服务！"
        return 1
    fi
}

start_service() {
    if check_status; then
        log "服务已在运行，无需重复启动。"
        return 0
    fi

    log "检查端口是否被占用..."
    if ! check_port; then
        return 1
    fi

    log "启动 $SERVICE_NAME 服务..."

    $GUNICORN_CMD \
        --daemon \
        --access-logfile "$ACCESS_LOG" \
        --error-logfile "$ERROR_LOG" \
        --name "$SERVICE_NAME" \
        --pid "$PID_FILE"

    local exit_code=$?
    if [ $exit_code -ne 0 ]; then
        log "❌ Gunicorn 启动失败，退出码: $exit_code"
        tail -n 20 "$ERROR_LOG"
        return 1
    fi

    sleep 2
    if check_status; then
        local pids=$(get_pids)
        log "✅ 服务启动成功 (PID: $pids)"
        return 0
    else
        log "❌ 服务启动失败，请查看 error.log"
        tail -n 20 "$ERROR_LOG"
        return 1
    fi
}

# ================ 主逻辑 ================
case "$1" in
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    restart)
        stop_service && start_service
        ;;
    status)
        check_status
        ;;
    cleanlogs)
        clean_logs
        ;;
esac
        echo "用法: $0 {start|stop|restart|status|clean_logs}"
        exit 1
        ;;
esac

exit $?
